package com.atguigu.edu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.app.BaseApp;
import com.atguigu.edu.bean.UserLoginBean;
import com.atguigu.edu.common.Constant;
import com.atguigu.edu.util.AtguiguUtil;
import com.atguigu.edu.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsUserUserLoginWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsUserUserLoginWindow().init(4004,2,
                "DwsUserUserLoginWindow", Constant.TOPIC_DWD_TRAFFIC_PAGE);
    }
    @Override
    public void handle(StreamExecutionEnvironment ev, DataStreamSource<String> stream) {
        //过滤出用户登录的数据
        SingleOutputStreamOperator<JSONObject> userLoginLogStream = filterUserLoginLog(stream);
        //封装数据为pojo
        SingleOutputStreamOperator<UserLoginBean> beanStream = parseToPojo(userLoginLogStream);
        //开窗聚合
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(beanStream);
        //写到clickhouse
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_user_login_window",
                UserLoginBean.class));
    }

    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> beanStream) {
        return beanStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean value1, UserLoginBean value2) throws Exception {
                        value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                        value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                        value1.setTs(System.currentTimeMillis());
                        return value1;
                    }
                }, new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void process(Context context,
                                        Iterable<UserLoginBean> iterable,
                                        Collector<UserLoginBean> collector) throws Exception {
                        UserLoginBean bean = iterable.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(context.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(context.window().getEnd()));
                        collector.collect(bean);
                    }
                });
    }

    private SingleOutputStreamOperator<UserLoginBean> parseToPojo(SingleOutputStreamOperator<JSONObject> userLoginLogStream) {
         return userLoginLogStream.keyBy(obj->obj.getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {

                    private ValueState<String> dateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        dateState = getRuntimeContext().getState(new ValueStateDescriptor
                                <String>("dateState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject jsonObject,
                                               Context context,
                                               Collector<UserLoginBean> collector) throws Exception {
                        //获取给参数值
                        Long backCt = 0l;
                        Long uuCt = 0l;
                        Long ts = jsonObject.getLong("ts");
                        String today = AtguiguUtil.tsToDate(ts);
                        if (!today.equals(dateState.value())){
                            uuCt = 1l;
                            if (dateState.value() != null) {
                                if ((ts - AtguiguUtil.dateToTs(dateState.value())) / 1000 / 60 / 60 / 24 > 7){
                                    backCt = 1l;
                                }
                            }
                            dateState.update(today);
                        }
                        if (uuCt==1)
                        collector.collect(new UserLoginBean("","",backCt,uuCt,ts));
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> filterUserLoginLog(DataStreamSource<String> stream) {
        return stream.map(JSON::parseObject)
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((obj,ts)->obj.getLong("ts"))
                        .withIdleness(Duration.ofSeconds(60)))
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        return (value.getString("last_page_id") == null ||
                                "login".equals(value.getString("last_page_id")))
                                && value.getString("uid") != null;
                    }
                });
    }
}